package com.atguigu.springcloud.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author csc
 * @Date 2023/3/11 0011 20:44
 * @Version 1.0
 */
@RestController
public class PaymentController
{
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody  Payment payment){
        int i = paymentService.create(payment);
        if(i>0){
            return new CommonResult(200,"1新增成功 serverPort"+serverPort);
        }else{
            return new CommonResult(201,"失败");
        }
    }//end create

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentByid(id);


        if(payment != null){
            return new CommonResult(200,"查询成功哈哈哈 serverPort:"+serverPort,payment);
        }else{
            return new CommonResult(201,"失败");
        }
    }//end getPaymentById


    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        //获取服务清单列表
        List<String> services = discoveryClient.getServices();
        for (String element: services) {
            System.out.println("*******element:"+element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance: instances) {
            System.out.println(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return discoveryClient;
    }//end


    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }



    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout(){
        ThreadUtil.sleep(3000);
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin()
    {
        return "hi,i`am pamentzipkin server fall back, welcome to csc，哈哈哈";
    }


    public static void main(String[] args) {
        ThreadUtil.execAsync(()->{
            System.out.println("你好");
        });
    }

}
